package com.chenfan.magic.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuming
 * @date 2021-04-08 16:40
 */
@Configuration
public class Redis2Config {

    /**
     * 最大活跃数
     */
    @Value("${spring.redis.jedis.pool.max-active:8}")
    private int maxActive;

    /**
     * 最大等待数
     */
    @Value("${spring.redis.jedis.pool.max-wait:-1}")
    private int maxWait;

    /**
     * 最大核心线程数
     */
    @Value("${spring.redis.jedis.pool.max-idle:8}")
    private int maxIdle;

    /**
     * 最小核心线程数
     */
    @Value("${spring.redis.jedis.pool.min-idle:0}")
    private int minIdle;

    /**
     * redis连接的超时时长
     */
    @Value("${spring.redis.timeout:5}")
    private int timeOut;

    /**
     * redis连接的库
     */
    @Value("${spring.redis.database:0}")
    private int database;
    /**
     * 节点配置
     */
    @Value("${spring.redis.cluster.nodes}")
    private String nodes;

    /**
     * 最大连接转移数
     */
    @Value("${spring.redis.cluster.max-redirects:3}")
    private int maxRedirects;

    /**
     * redis的连接密码
     */
    @Value("${spring.redis.password}")
    private String password;

    /**
     * 创建redisTemplate连接模板
     *
     * @return
     */
    @Primary
    @Bean
    @Qualifier("redisTemplate2")
    public RedisTemplate<String, Object> redisTemplate2() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory2());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }

    /**
     * k-v的序列化
     *
     * @return
     */
    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer2() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }

    /**
     * 连接配置
     *
     * @return
     */
    @Primary
    @Bean
    @Qualifier("redisConnectionFactory2")
    public RedisConnectionFactory connectionFactory2() {
        Map<String, Object> source = new HashMap<String, Object>(16);
        RedisClusterConfiguration redisClusterConfiguration;
        RedisStandaloneConfiguration redisStandaloneConfiguration;
        //连接池配置
        GenericObjectPoolConfig genericObjectPoolConfig =
                new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMinIdle(minIdle);

        //redis客户端配置
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder
                builder = LettucePoolingClientConfiguration.builder().
                commandTimeout(Duration.ofSeconds(timeOut));
        builder.poolConfig(genericObjectPoolConfig);
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();

        //集群模式

        source.put("spring.redis.cluster.nodes", nodes);
        source.put("spring.redis.cluster.max-redirects", maxRedirects);
        redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
        if (!StringUtils.isEmpty(password)) {
            redisClusterConfiguration.setPassword(password);
        }
        //根据配置和客户端配置创建连接工厂
        LettuceConnectionFactory lettuceConnectionFactory = new
                LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
        return lettuceConnectionFactory;

    }
}
